<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommandEnum;
use app\enum\CommonEnum;
use app\model\ClientAccountModel;
use app\model\OeAssetsModel;
use app\model\OeOptimizedGoalNewModel;
use app\service\client\AccountService;
use app\service\ocean\AdvertiserService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Db;

/**
 * @deprecated
 */
class OeOptimizedGoalWork extends BaseWork
{
    public const REDIS_TASK_KEY = CommandEnum::OE_TASK_LIST_KEY[3];

    public array $clientAccountInfo = [];

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_optimized_goal_work');
        // 设置参数
        $this->setDescription('巨量获取可用优化目标（巨量广告升级版）');

        // 设置参数
        $this->addArgument('advertiser_id', null, '账户id')
            ->setHelp('php think oe_optimized_goal_work [advertiser_id]');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $output->writeln('=======巨量引擎-获取可用优化目标开始' . date('Y-m-d H:i:s', time()) . '=======');
        //        $advertiserId = $input->getArgument('advertiser_id');
        $redisKey = self::REDIS_TASK_KEY;
        $redis = Cache::store('redis')->handler();
        $count = 0;
        $appPromotionType = [
            'DOWNLOAD', 'LAUNCH', 'RESERVE',
        ];
        try {
            while (true) {
                if ($count >= 100) {
                    break;
                }
                $advertiserId = $redis->lPop($redisKey);
                if ($advertiserId) {
                    $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
                    if (! $token) {
                        break;
                    }
                    $this->clientAccountInfo = $this->_getClientAccountInfo($advertiserId);
                    // 获取资产信息
                    $assetsData = $this->_getAssets($advertiserId);
                    if ($assetsData) {
                        $params = [];
                        foreach ($assetsData as $assets) {
                            if ($assets['asset_type'] == 'APP') {
                                $assetArr = json_decode($assets['app'], true);
                                $param = [
                                    'landing_type' => 'APP',
                                    'ad_type' => 'ALL',
                                    'asset_type' => 'APP',
                                ];
                            } elseif ($assets['asset_type'] == 'THIRD_EXTERNAL') {
                                $assetArr = json_decode($assets['landing_pages'], true);
                                $param = [
                                    'landing_type' => 'LINK',
                                    'ad_type' => 'ALL',
                                    'asset_type' => 'THIRDPARTY',
                                ];
                            }
                            if (! empty($assetArr)) {
                                foreach ($assetArr as $asset) {
                                    $param['asset_id'] = $asset['asset_id'];
                                    if ($assets['asset_type'] == 'APP') {
                                        foreach ($appPromotionType as $type) {
                                            $param['app_type'] = $asset['app_type'];
                                            $param['app_promotion_type'] = $type;
                                            $params[] = $param;
                                        }
                                    } else {
                                        $params[] = $param;
                                    }

                                }
                            }
                        }
                        if (empty($params)) {
                            continue;
                        }
                        foreach ($params as $param) {
                            // 请求接口
                            $result = $this->_getAppData($token, $advertiserId, $param);
                            if (! $result) {
                                $err = ['params' => ['token' => $token, 'advertiserId' => $advertiserId], 'response' => AdvertiserService::getError(0)];
                                $output->writeln('=======error:' . json_encode($err, JSON_UNESCAPED_UNICODE) . '=======' . PHP_EOL);
                                break;
                            }
                            $list = $result['data']['goals'];
                            if (count($list) == 0) {
                                break;
                            }
                            foreach ($list as $v) {
                                $v['asset_id'] = $asset['asset_id'];
                                $v['asset_type'] = $param['asset_type'];
                                $v['landing_type'] = $param['landing_type'];
                                $v['ad_type'] = $param['ad_type'];
                                $v['app_type'] = ! empty($param['app_type']) ? $param['app_type'] : '';
                                $v['app_promotion_type'] = ! empty($param['app_promotion_type']) ? $param['app_promotion_type'] : '';
                                $dataInfo = $this->_getAppInfo($advertiserId, $v);
                                if (! empty($dataInfo)) {
                                    $res = $this->_updateAdvertiserData($dataInfo['id'], $v);
                                } else {
                                    $res = $this->_insertAdvertiserData($advertiserId, $v);
                                }
                                if (! $res) {
                                    echo self::getError(0);
                                }
                            }
                        }
                    }
                    ++$count;
                } else {
                    break;
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }


        $output->writeln('=======巨量引擎-获取可用优化目标结束' . date('Y-m-d H:i:s', time()) . '=======');
    }

    /**
     * 获取资产信息.
     * @return bool|mixed|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function _getAssets(string $advertiserId = '')
    {
        // 获取资产信息
        return OeAssetsModel::where('advertiser_id', $advertiserId)->select();
    }

    /**
     * @return bool|mixed|string
     */
    private function _getAppData(string $token = '', string $advertiserId = '', array $params = [])
    {
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params['advertiser_id'] = $advertiserId;
        return AdvertiserService::getOptimizedGoal($headers, $params);
    }

    /**
     * 判断是否需要更新.
     * @param array $oldData 旧数据
     * @param array $newData 新数据
     */
    private function _isDataUpdate(array $oldData = [], array $newData = []): bool
    {
        $one = $oldData['update_time'] == $newData['update_time'];
        $two = $oldData['reason'] == $newData['reason'];
        $thr = $oldData['status'] == $newData['status'];
        $fur = $oldData['version_name'] == $newData['version_name'];
        $fiv = $oldData['channel_id'] == $newData['channel_id'];
        $six = $oldData['download_url'] == $newData['download_url'];
        $sen = $oldData['remark'] == $newData['remark'];

        if ($one && $two && $thr && $fur && $fiv && $six && $sen) {
            return true;
        }

        return false;
    }

    /**
     * 获取信息.
     * @param string $advertiserId 账户id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _getAppInfo(string $advertiserId = '', array $info = []): array
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
            ['asset_id', '=', $info['asset_id']],
            ['landing_type', '=', $info['landing_type']],
            ['asset_type', '=', $info['asset_type']],
            ['external_action', '=', $info['external_action']],
            ['app_type', '=', $info['app_type']],
            ['app_promotion_type', '=', $info['app_promotion_type'] ?? ''],
        ];

        $info = (new OeOptimizedGoalNewModel())->where($where)->field(true)->find();
        if (! $info) {
            return [];
        }

        return $info->toArray();
    }

    /**
     * 修改信息.
     * @param int $id 主键ID
     * @param array $info 信息数据
     */
    private function _updateAdvertiserData(int $id = 0, array $info = []): bool
    {
        try {
            $data = [
                'external_action' => $info['external_action'],
                'optimization_name' => $info['optimization_name'],
                'history_back' => $info['history_back'],
                'twenty_four_hour_back' => $info['twenty_four_hour_back'],
                'deep_goals' => $info['deep_goals'] ? json_encode($info['deep_goals'], JSON_UNESCAPED_UNICODE) : [],
                'update_time' => time(),
            ];
            Db::startTrans();
            $one = (new OeOptimizedGoalNewModel())->where('id', $id)->update($data);
            if ($one) {
                Db::commit();
                return true;
            }
            Db::rollback();
            return false;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 插入广告报表信息.
     * @param string $advertiserId 账户ID
     * @param array $info 信息数据
     * @deprecated
     */
    private function _insertAdvertiserData(string $advertiserId = '', array $info = []): bool
    {
        try {
            Db::startTrans();
            $data = [
                'advertiser_id' => $advertiserId,
                'account_id' => $this->clientAccountInfo['id'],
                'landing_type' => $info['landing_type'],
                'ad_type' => $info['ad_type'],
                'asset_type' => $info['asset_type'],
                'app_type' => $info['app_type'],
                'app_promotion_type' => $info['app_promotion_type'],
                'asset_id' => $info['asset_id'],
                'external_action' => $info['external_action'],
                'optimization_name' => $info['optimization_name'],
                'history_back' => $info['history_back'],
                'twenty_four_hour_back' => $info['twenty_four_hour_back'],
                'deep_goals' => $info['deep_goals'] ? json_encode($info['deep_goals'], JSON_UNESCAPED_UNICODE) : [],
                'create_time' => time(),
            ];
            $insertId = (new OeOptimizedGoalNewModel())->insertGetId($data);
            if ($insertId <= 0) {
                Db::rollback();
                return false;
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dump($e);
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取账户信息.
     * @param string $advertiserId 账户ID
     * @throws
     */
    private function _getClientAccountInfo(string $advertiserId = ''): array
    {
        $info = (new ClientAccountModel())->where('advertiser_id', $advertiserId)->field(true)->find();
        if (! $info) {
            return [];
        }
        return $info->toArray();
    }
}
